package com.wyw.hemerocallis.service.async;

import com.wyw.hemerocallis.constant.AsyncTaskStatusEnum;
import com.wyw.hemerocallis.goods.GoodsInfo;
import com.wyw.hemerocallis.vo.AsyncTaskInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 异步任务执行管理器(暴露给前端)代理设计模式
 *      对异步任务进行包装管理，记录并塞入异步任务执行信息
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@Component
public class AsyncTaskManager {

    /**
     * 异步任务执行信息的容器
     */
    private final Map<String, AsyncTaskInfo> taskInfoContainer =
            new HashedMap<>(16);

    @Autowired
    private IAsyncService asyncService;

    /**
     * 初始化异步任务
     * @return
     */
    public AsyncTaskInfo initTask() {
        AsyncTaskInfo taskInfo = new AsyncTaskInfo();
        taskInfo.setTaskId(UUID.randomUUID().toString());
        taskInfo.setStatus(AsyncTaskStatusEnum.STARTED);
        taskInfo.setStartTime(new Date());

        //初始化时需要把异步任务执行信息放到存储容器中
        taskInfoContainer.put(taskInfo.getTaskId(), taskInfo);
        return taskInfo;
    }

    /**
     * 提交异步任务
     * @param goodsInfos
     * @return
     */
    public AsyncTaskInfo submit(List<GoodsInfo> goodsInfos) {
        //初始化一个异步任务监控信息
        AsyncTaskInfo taskInfo = initTask();
        asyncService.asyncImportGoods(goodsInfos, taskInfo.getTaskId());
        return taskInfo;
    }

    /**
     * 设置异步任务执行状态信息
     * */
    public void setTaskInfo(AsyncTaskInfo taskInfo) {
        taskInfoContainer.put(taskInfo.getTaskId(), taskInfo);
    }

    /**
     * 获取异步任务执行状态信息
     * */
    public AsyncTaskInfo getTaskInfo(String taskId) {
        return taskInfoContainer.get(taskId);
    }

}
